<?php
/**
 * File: User.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 18:07
 */

namespace Common\Service;

use Think\Page;

class User extends Base
{

    /**
     * 登录方法
     * @param $userId
     */
    public function login($userId)
    {
        //生成auth_key
        $authKey = $this->uniqueAuthKey();
        //写入auth_key,生成cookie
        M('user')->save(['id' => $userId, 'auth_key' => $authKey]);
        $expireTime = C('USER_TOKEN_EXPIRE');
        cookie('_token', $authKey, ['httponly' => true, 'expire' => $expireTime]);
        cookie('_token_expire', time() + $expireTime, ['httponly' => true, 'expire' => $expireTime]);

    }

    public function uniqueAuthKey()
    {
        $model = M('user');
        $closure = function () {
            return generate_random_string(45);
        };
        return $this->uniqueKey($model, 'auth_key', $closure);
    }

    /**
     * 获取用户（钉钉userid）
     * @param $userId
     * @return mixed
     */
    public function getUserByUserId($userId)
    {
        return M('user')
            ->where(['userid' => $userId, 'deleted_at' => 0])
            ->find();
    }

    /**
     * 获取用户（用户id）
     * @param $id
     * @return mixed
     */
    public function getUserById($id)
    {
        return M('user')
            ->where(['id' => $id, 'deleted_at' => 0])
            ->find();

    }

    /**
     * 获取用户（token）
     * @param $authKey
     * @return mixed
     */
    public function getUserByAuthKey($authKey)
    {
        return M('user')
            ->where(['auth_key' => $authKey, 'deleted_at' => 0])
            ->find();
    }

    /**
     * 获取用户列表
     * @param $search
     * @param $departmentId
     * @param $notInProjectId
     * @return mixed
     */
    public function getUserList($search, $departmentId, $notInProjectId)
    {
        $model = M('user')->field('id,name,avatar,mobile,email,department,position');
        if (!empty($departmentId)) {
            $subQuery = M('userDepartment')
                ->field('user_userid as userid')
                ->where(['department_id' => $departmentId])
                ->select(false);
            $model->where(['userid' => ['exp', "in ({$subQuery})"]]);
        }
        if (!empty($notInProjectId)) {
            $projectSubQuery = M('projectMember')
                ->field('user_id id')
                ->where(['project_id' => $notInProjectId])
                ->select(false);
            $model->where(['id' => ['exp', "not in ({$projectSubQuery})"]]);
        }
        if (!empty($search)) {
            $map['name'] = ['like', "%{$search}%"];
            $map['mobile'] = ['like', "%{$search}%"];
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
            $model->where($where);
        }
        return $model->select();

    }

    /**
     * 获取部门列表
     * @return mixed
     */
    public function getDepartmentList()
    {
        return M('department')->field('id,name')->select();
    }

    /**
     * 获取个人中心信息
     */
    public function getPersonalInfo()
    {
        //用户信息
        $user = user()->getUser();
        $userInfo['name'] = $user['name'];
        $userInfo['avatar'] = $user['avatar'];
        $userInfo['mobile'] = $user['mobile'];
        $userInfo['email'] = $user['email'];
        $userInfo['department'] = $user['department'];
        $userInfo['position'] = $user['position'];
        $userInfo['signature'] = $user['signature'];
        $data['user'] = $userInfo;
        //用户积分
        $data['points']['balance'] = $user['balance'];;
        //冻结积分
        $freezePoints = M('projectPointsAllocateRecord')
            ->where(['user_id' => $user['id'], 'status' => ['in', [0, 3]]])
            ->sum('points');
        $data['points']['freeze'] = number_format($freezePoints, 2);
        //历史总积分
        $totalPoints = M('projectPointsAllocateRecord')
            ->where(['user_id' => $user['id'], 'status' => ['in', [0, 1, 3]]])
            ->sum('points');
        $data['points']['total'] = number_format($totalPoints, 2);

        return $data;
    }

    /**
     * 获取用户积分明细
     * @param $type
     * @return mixed
     */
    public function getUserPointsList($type)
    {
        if ($type == 0) {
            $status = [0];
        } else {
            $status = [1, 2];
        }
        $userId = user()->id;
        $count = M('projectPointsAllocateRecord')
            ->where(['user_id' => $userId, ['status' => ['in', $status]]])->count();
        $param['type'] = $type;
        $page = new Page($count, $this->pageSize, $param);

        $list = M('projectPointsAllocateRecord')
            ->alias('ar')
            ->join('left join project p on ar.project_id=p.id')
            ->join('left join user u on ar.allocate_user_id=u.id')
            ->field(['ar.id,ar.points,ar.created_at,ar.status,ar.refuse_reason,u.name user_name,p.name project_name'])
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('ar.created_at desc')
            ->where(['ar.user_id' => $userId, 'ar.status' => ['in', $status]])
            ->select();

        return ['list' => $list, 'show' => $page->show()];
    }

}